package org.zero.controller;

import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.zero.model.R;

/**
 * @author Zero (cnzeropro@qq.com)
 * @date 2021/10/12 18:56
 */
@RestController
@RequestMapping("file")
public class FileController {

    @PostMapping("upload")
    public R<String> upload(HttpServletRequest request,
                            @RequestParam("file") MultipartFile multipartFile) {

        return R.<String>builder()
                .code(200)
                .message("文件上传成功")
                .data(multipartFile.getOriginalFilename())
                .build();
    }

    public boolean saveMultipartFile(HttpServletRequest request, MultipartFile multipartFile) {
        if (!multipartFile.isEmpty()) {
            try {
                // 设置文件存放路径
                String path = request.getServletContext().getRealPath("/uploads/");
                File file = new File(path);
                if (!file.exists()) {
                    boolean mkdirs = file.mkdirs();
                }

                String name = UUID.randomUUID().toString().replace("-", "") + "_" + multipartFile.getOriginalFilename();
                multipartFile.transferTo(new File(path, name));
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
